import request from '../../utils/request'
import { showSuccess, showError, showLoading, hideLoading, formatTime } from '../../utils/util'

Page({
  data: {
    postId: null,
    post: null,
    members: [],
    isLiked: false,
    loading: true
  },

  onLoad(options) {
    this.postId = options.id
    this.loadPostDetail()
  },

  onReady() {
    wx.setNavigationBarTitle({
      title: '帖子详情'
    })
  },

  async loadPostDetail() {
    try {
      showLoading('加载中...')

      const userId = wx.getStorageSync('userId') || 1
      const [detail, members] = await Promise.all([
        request.get(`/team/${this.postId}/detail`, { userId }),
        request.get(`/team/${this.postId}/members`)
      ])

      if (detail && detail.post) {
        this.setData({
          post: {
            ...detail.post,
            startTime: formatTime(detail.post.startTime),
            endTime: formatTime(detail.post.endTime),
            createTime: formatTime(detail.post.createTime)
          },
          members: detail.members || [],
          isLiked: detail.isLiked || false,
          loading: false
        })
      } else {
        showError('帖子不存在')
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }

      hideLoading()
    } catch (error) {
      hideLoading()
      showError('加载失败')
      this.setData({ loading: false })
      console.error('加载帖子详情失败:', error)
    }
  },

  async onLike() {
    try {
      if (this.data.isLiked) {
        await request.post(`/posts/${this.postId}/unlike`)
        this.setData({
          isLiked: false,
          'post.likeCount': this.data.post.likeCount - 1
        })
        showSuccess('取消点赞')
      } else {
        await request.post(`/posts/${this.postId}/like`)
        this.setData({
          isLiked: true,
          'post.likeCount': this.data.post.likeCount + 1
        })
        showSuccess('点赞成功')
      }
    } catch (error) {
      showError('操作失败')
    }
  },

  async onApply() {
    try {
      const result = await request.post('/team/apply', {
        postId: this.postId,
        message: '我想加入这个活动'
      })

      if (result.success) {
        showSuccess('申请成功，等待队长审核')
      } else {
        showError('申请失败，请重试')
      }
    } catch (error) {
      if (error.code === 400) {
        showError('您已经申请过该活动')
      } else {
        showError('申请失败')
      }
    }
  },

  onShareAppMessage() {
    const post = this.data.post
    return {
      title: post ? post.title : '组队找伙伴',
      path: `/pages/post-detail/post-detail?id=${this.postId}`,
      imageUrl: post && post.avatar ? post.avatar : '/images/default-avatar.png'
    }
  },

  onShareTimeline() {
    const post = this.data.post
    return {
      title: post ? post.title : '组队找伙伴',
      imageUrl: post && post.avatar ? post.avatar : '/images/default-avatar.png'
    }
  }
})